package com.unience.aws.monitor;

import java.io.File;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.unience.aws.monitor.model.LoadInfo;
import com.unience.aws.monitor.model.MonitorEc2Instance;
import com.unience.ddns.IpHelper;

public class SshProccess extends Thread {

	private static Log log = LogFactory.getLog(SshProccess.class);
	private MonitorEc2Instance instance;
	
	private boolean stop = false;

	public SshProccess(MonitorEc2Instance inst) {
		instance = inst;
	}

	public void run() {
		
		try {
			sleep(5000);
		} catch (InterruptedException e) {

		}
		
		StringBuffer keyPath = new StringBuffer();
		
		keyPath.append(this.instance.getKeyDir()).append('/').append(instance.getInstance().getKeyName());
		
		File key = new File(keyPath.toString());
		if (!key.exists()){
			stop =true;
			log.error("FILE KEY DO NOT EXITS !!!! " + key.getAbsolutePath());
		}

		while (!stop) {
		
			
			if (instance.getInstance() != null){
				
				if (instance.getInstance().getStateCode() == 16 ){

				log.debug("Connecting SSH " + instance.getInstance().getInstanceId());
				
				SshExec ssh = new SshExec();
	
				ssh.connect("root", IpHelper.getIp(instance.getInstance()
						.getDnsName()), keyPath.toString());
	
				String upTime = ssh.exec("uptime");
	
				parseUptime(instance, upTime);
				log.debug(upTime);
				
			//	String user_data =executeCommand(instance.getInstance()
			//			.getDnsName(), keyPath.toString(), "curl  http://169.254.169.254/latest/user-data");
				String user_data =executeCommand(instance.getInstance()
						.getDnsName(), keyPath.toString(), "more /var/user-data");
			
				log.debug(user_data);
				instance.setUserData(user_data);
	
				ssh.close();
				
				}
			}
		
		
			try {
				sleep(30000);
			} catch (InterruptedException e) {
	
			}
		}

	}

	private void parseUptime(MonitorEc2Instance inst, String upTime) {

		final String LOADAVERAGE = "load average:";

		if ((upTime != null) && (!upTime.isEmpty())) {
			int index = upTime.indexOf(LOADAVERAGE);

			String loads = upTime.substring(index + LOADAVERAGE.length());

			StringTokenizer token = new StringTokenizer(loads, ",");

			String load1M = token.nextToken();
			String load5M = token.nextToken();
			String load15M = token.nextToken();
			load15M = load15M.substring(0, load15M.length() - 1);
			LoadInfo loadInfo = inst.getMonitorInfo().getLoadInfo();
			loadInfo.setLoad1m(load1M);
			loadInfo.setLoad5m(load5M);
			loadInfo.setLoad15m(load15M);

		}

	}
	
	
	private String executeCommand(String ip, String key, String command){
		SshExec ssh = new SshExec();
		
		ssh.connect("root", ip,key);
		
		return  ssh.exec(command); 		
	}
	
	public void stopSsh() {
		this.stop = true;
		try {
			this.join();
		} catch (InterruptedException e) {
			log.warn(e);
		}
	}
}
